'use client'

import { useState } from 'react'
import { Wand2, Image, Loader2, Download } from 'lucide-react'

interface IllustrationData {
  imageUrl: string
  source: string
  prompt: string
  theme: string
  ageGroup: string
  illustrationType: string
  timestamp: string
}

/**
 * OpenAI插图生成示例组件
 * 展示如何在React组件中集成OpenAI插图生成功能
 */
export default function OpenAIIllustrationExample() {
  const [isGenerating, setIsGenerating] = useState(false)
  const [illustration, setIllustration] = useState<IllustrationData | null>(null)
  const [error, setError] = useState<string | null>(null)

  // 示例故事内容
  const exampleStories = [
    {
      theme: 'friendship',
      ageGroup: '3-5',
      content: '小兔子和小鸟成为了好朋友，它们一起在森林里玩耍。',
      title: '友谊故事'
    },
    {
      theme: 'courage',
      ageGroup: '6-8',
      content: '小熊克服了害怕黑暗的恐惧，学会了勇敢面对困难。',
      title: '勇气故事'
    },
    {
      theme: 'kindness',
      ageGroup: '9-12',
      content: '小鹿帮助受伤的小动物，展现了善良和爱心。',
      title: '善良故事'
    }
  ]

  /**
   * 生成插图
   * @param story 故事数据
   */
  const generateIllustration = async (story: typeof exampleStories[0]) => {
    setIsGenerating(true)
    setError(null)
    setIllustration(null)

    try {
      const response = await fetch('/api/generate-illustration', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          theme: story.theme,
          ageGroup: story.ageGroup,
          storyContent: story.content,
          illustrationType: 'main',
          useOpenAI: true
        }),
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || '生成插图失败')
      }

      const data = await response.json()
      setIllustration(data)
    } catch (error) {
      console.error('生成插图失败:', error)
      setError(error instanceof Error ? error.message : '未知错误')
    } finally {
      setIsGenerating(false)
    }
  }

  /**
   * 下载图片
   * @param imageUrl 图片URL
   * @param filename 文件名
   */
  const downloadImage = async (imageUrl: string, filename: string) => {
    try {
      const response = await fetch(imageUrl)
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = filename
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
    } catch (error) {
      console.error('下载图片失败:', error)
    }
  }

  return (
    <div className="space-y-8">
      {/* 组件标题 */}
      <div className="text-center">
        <div className="flex items-center justify-center space-x-3 mb-4">
          <div className="p-2 bg-green-100 rounded-lg">
            <Wand2 className="h-6 w-6 text-green-600" />
          </div>
          <h2 className="text-2xl font-bold text-gray-900">
            OpenAI插图生成示例
          </h2>
        </div>
        <p className="text-gray-600">
          点击下方按钮测试不同主题的OpenAI插图生成功能
        </p>
      </div>

      {/* 示例故事列表 */}
      <div className="grid md:grid-cols-3 gap-6">
        {exampleStories.map((story, index) => (
          <div key={index} className="bg-white rounded-xl shadow-lg p-6">
            <h3 className="text-lg font-semibold text-gray-900 mb-3">
              {story.title}
            </h3>
            <p className="text-gray-600 text-sm mb-4">
              {story.content}
            </p>
            <div className="text-xs text-gray-500 mb-4">
              <div>主题: {story.theme}</div>
              <div>年龄组: {story.ageGroup}</div>
            </div>
            <button
              onClick={() => generateIllustration(story)}
              disabled={isGenerating}
              className="w-full btn-primary flex items-center justify-center space-x-2"
            >
              {isGenerating ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Image className="h-4 w-4" />
              )}
              <span>
                {isGenerating ? '生成中...' : '生成插图'}
              </span>
            </button>
          </div>
        ))}
      </div>

      {/* 错误显示 */}
      {error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4">
          <h3 className="font-medium text-red-800 mb-2">生成失败</h3>
          <p className="text-red-700 text-sm">{error}</p>
        </div>
      )}

      {/* 生成的插图显示 */}
      {illustration && (
        <div className="bg-white rounded-xl shadow-lg p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold text-gray-900">
              生成的插图
            </h3>
            <button
              onClick={() => downloadImage(illustration.imageUrl, `illustration-${Date.now()}.png`)}
              className="btn-secondary flex items-center space-x-2"
            >
              <Download className="h-4 w-4" />
              <span>下载</span>
            </button>
          </div>

          <div className="grid md:grid-cols-2 gap-6">
            {/* 图片显示 */}
            <div>
              <img
                src={illustration.imageUrl}
                alt="AI生成的插图"
                className="w-full rounded-lg shadow-md"
              />
              <div className="mt-2 text-center">
                <span className={`inline-block px-2 py-1 rounded text-xs ${
                  illustration.source === 'openai' 
                    ? 'bg-green-100 text-green-800' 
                    : 'bg-yellow-100 text-yellow-800'
                }`}>
                  {illustration.source === 'openai' ? 'OpenAI DALL-E 3' : '备用方案'}
                </span>
              </div>
            </div>

            {/* 生成信息 */}
            <div className="space-y-3">
              <div>
                <h4 className="font-medium text-gray-900 mb-2">生成信息</h4>
                <div className="text-sm space-y-1">
                  <div>
                    <span className="font-medium text-gray-700">主题:</span>
                    <span className="ml-2 text-gray-600">{illustration.theme}</span>
                  </div>
                  <div>
                    <span className="font-medium text-gray-700">年龄组:</span>
                    <span className="ml-2 text-gray-600">{illustration.ageGroup}</span>
                  </div>
                  <div>
                    <span className="font-medium text-gray-700">类型:</span>
                    <span className="ml-2 text-gray-600">{illustration.illustrationType}</span>
                  </div>
                  <div>
                    <span className="font-medium text-gray-700">时间:</span>
                    <span className="ml-2 text-gray-600">
                      {new Date(illustration.timestamp).toLocaleString()}
                    </span>
                  </div>
                </div>
              </div>

              <div>
                <h4 className="font-medium text-gray-900 mb-2">使用的提示词</h4>
                <div className="bg-gray-50 rounded-lg p-3">
                  <p className="text-sm text-gray-700 whitespace-pre-wrap">
                    {illustration.prompt}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 使用说明 */}
      <div className="bg-blue-50 border border-blue-200 rounded-lg p-6">
        <h3 className="font-medium text-blue-900 mb-3">使用说明</h3>
        <div className="text-sm text-blue-800 space-y-2">
          <p>
            <strong>功能特点：</strong>
            本组件展示了如何在React应用中集成OpenAI插图生成功能
          </p>
          <p>
            <strong>API调用：</strong>
            通过 <code className="bg-blue-100 px-1 rounded">/api/generate-illustration</code> 接口调用OpenAI DALL-E 3
          </p>
          <p>
            <strong>错误处理：</strong>
            包含完整的错误处理和用户友好的错误提示
          </p>
          <p>
            <strong>下载功能：</strong>
            支持将生成的图片下载到本地
          </p>
        </div>
      </div>
    </div>
  )
} 